package com.matt.controller.pad;

import com.dotflat.milestone.po.CheckSheet;
import com.dotflat.milestone.po.CheckSheetDimension;
import com.dotflat.milestone.po.CheckSheetTarget;
import com.dotflat.milestone.service.CheckSheetExportService;
import com.matt.commons.dto.sso.StaffDTO;
import com.matt.commons.model.StatusResponse;
import com.matt.commons.page.PagerQuery;
import com.matt.domain.courseV2.DevelopReview;
import com.matt.domain.courseV2.DevelopReviewItem;
import com.matt.domain.courseV2.po.DevelopCountPO;
import com.matt.domain.courseV2.po.DevelopDetailsListPO;
import com.matt.domain.courseV2.po.DevelopDetailsPO;
import com.matt.domain.courseV2.po.DevelopReviewPO;
import com.matt.domain.courseV2.vo.AddUserMonthVO;
import com.matt.foundation.ext.aliyun.OSSProcessService;
import com.matt.foundation.model.MemVerificationCache;
import com.matt.foundation.utils.DateUtil;
import com.matt.service.courseV2.DevelopReviewService;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import static com.matt.foundation.constant.RequestConstant.TICKET;


@RestController
@RequestMapping("/pad/developReview")
@Slf4j
@Api(tags = "教学 - 发展检核")
public class PadDevelopReviewController {

    @Autowired
    private DevelopReviewService developReviewService;

    @Autowired
    private  CheckSheetExportService checkSheetExportService;

    @Autowired
    protected MemVerificationCache cache;

    @Autowired
    private OSSProcessService ossProcessService;

    @Value("${aliyun.oss.fileServerPrefix}")
    private String IMG_SERVICE_PREFIX;

    @ApiOperation(value = "月份 - 列表")
    @PostMapping("/month_list")
    @ApiResponses({
            @ApiResponse(code = 000000, message = "successful", response = DevelopReview.class),
    })
    public StatusResponse monthList(Integer type) {
        List<DevelopReview> list = developReviewService.monthList(type);
        return StatusResponse.success(list);
    }

    @ApiOperation(value = "月份 - 默认项目")
    @PostMapping("/month_item_list")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "header", name = "ticket", value = "票据", required = true, dataType = "string"),
            @ApiImplicitParam(paramType = "query", name = "developId", value = "发展核减月ID", required = true, dataType = "string"),
    })
    @ApiResponses({
            @ApiResponse(code = 000000, message = "successful", response = DevelopReviewPO.class),
    })
    public StatusResponse monthItemList(@RequestHeader(TICKET) String ticket,String developId) {
        List<DevelopReviewItem> list = developReviewService.monthItemList(developId);
        return StatusResponse.success(list);
    }


    @ApiOperation(value = "记录 - 添加")
    @PostMapping("/add_user_month")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "header", name = "ticket", value = "票据", required = true, dataType = "string"),
    })
    public StatusResponse add(@RequestHeader(TICKET) String ticket, AddUserMonthVO addUserMonth) {
        StaffDTO staff = cache.getStaff(ticket);
        String replaced="";
        if (StringUtils.isNotBlank(addUserMonth.getDevelopName())){
             replaced = addUserMonth.getDevelopName().replace("月", "");

        }
        developReviewService.addUserMonth1(staff, addUserMonth.getChildrenIds(), addUserMonth.getClassIds(),addUserMonth.getDevelopId(), staff.getRealName(),addUserMonth.getRemarks(),addUserMonth.getList(), Integer.valueOf(replaced));
        return StatusResponse.success("添加成功");
    }


    @ApiOperation(value = "班级人员 - 统计列表")
    @PostMapping("/count")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "header", name = "ticket", value = "票据", required = true, dataType = "string"),
            @ApiImplicitParam(paramType = "query", name = "classId", value = "班级ID", required = false, dataType = "string"),
            @ApiImplicitParam(paramType = "query", name = "name", value = "学生名称", required = false, dataType = "string"),
    })
    @ApiResponses({
            @ApiResponse(code = 000000, message = "successful", response = DevelopCountPO.class),
    })
    public StatusResponse count(@RequestHeader(TICKET) String ticket, String classId, String name,PagerQuery pagerQuery) {
        StaffDTO staff = cache.getStaff(ticket);
        Page<DevelopCountPO> developCountPO = developReviewService.count( staff.getAreaId(), classId,name,pagerQuery);
        return StatusResponse.success(developCountPO);
    }


    @ApiOperation(value = "核检单人 - 详情列表")
    @PostMapping("/childrenDetailsList")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "header", name = "ticket", value = "票据", required = true, dataType = "string"),
            @ApiImplicitParam(paramType = "query", name = "childrenId", value = "宝宝ID", required = true, dataType = "string"),
    })
    @ApiResponses({
            @ApiResponse(code = 000000, message = "successful", response = DevelopDetailsListPO.class),
    })
    public StatusResponse childrenDetailsList(@RequestHeader(TICKET) String ticket, String childrenId,PagerQuery pagerQuery) {
        Page<DevelopDetailsListPO> list = developReviewService.childrenDetailsList( childrenId,pagerQuery);
        return StatusResponse.success(list);
    }


    @ApiOperation(value = "核检单人 - 详情")
    @PostMapping("/childrenDetails")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "header", name = "ticket", value = "票据", required = true, dataType = "string"),
            @ApiImplicitParam(paramType = "query", name = "developUserId", value = "核检记录ID", required = true, dataType = "string"),
    })
    @ApiResponses({
            @ApiResponse(code = 000000, message = "successful", response = DevelopDetailsPO.class),
    })
    public StatusResponse childrenDetails(@RequestHeader(TICKET) String ticket,String  developUserId) {
        DevelopDetailsPO developDetails = developReviewService.childrenDetails( developUserId);
        return StatusResponse.success(developDetails);
    }


    @ApiOperation(value = "核检单人 - 导出")
    @PostMapping("/exportChildrenDetails")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "header", name = "ticket", value = "票据", required = true, dataType = "string"),
            @ApiImplicitParam(paramType = "query", name = "developUserId", value = "核检记录ID", required = true, dataType = "string"),
    })
    @ApiResponses({
            @ApiResponse(code = 000000, message = "successful", response = DevelopDetailsPO.class),
    })
    public StatusResponse exportChildrenDetails(@RequestHeader(TICKET) String ticket,String  developUserId) {
        DevelopDetailsPO developDetails = developReviewService.childrenDetails( developUserId);

        CheckSheet sheet = new CheckSheet();
        sheet.setUuid(UUID.randomUUID().toString());  //可以用其他逻辑代替，只是用来区分临时文件的文件名
        sheet.setChildName(developDetails.getChildrenName());
        sheet.setChildMonth(String.valueOf(developDetails.getChildrenMonth())+"m");
        sheet.setSheetMonth(String.valueOf(developDetails.getMonth())+"m");
        sheet.setDevelopment(developDetails.getRemarks());
        List<CheckSheetDimension> list = new ArrayList<>();
        if (developDetails.getList().size()>0){
            String name  = "";

            List<CheckSheetTarget> targetList = new ArrayList<>();

            for (int i = 0; i <developDetails.getList().size() ; i++) {
                CheckSheetDimension checkSheetDimension = new CheckSheetDimension();
                if (!StringUtils.equals(name,developDetails.getList().get(i).getName())){
                    if (i==0){
                        name  = developDetails.getList().get(0).getName();
                        checkSheetDimension.setName(name);
                    }else {
                        checkSheetDimension.setName(name);
                        name = developDetails.getList().get(i).getName();
                        checkSheetDimension.setTargetList(targetList);
                        list.add(checkSheetDimension);
                        targetList= new ArrayList<>();
                    }
                }
                String states = "×";
                if (developDetails.getList().get(i).getStates()==1){
                    states= "○";
                }
                CheckSheetTarget checkSheetTarget = new CheckSheetTarget(states,developDetails.getList().get(i).getTarget(),developDetails.getList().get(i).getDetails());
                targetList.add(checkSheetTarget);
                if (i == developDetails.getList().size() -1){
                    checkSheetDimension.setName(developDetails.getList().get(i).getName());
                    checkSheetDimension.setTargetList(targetList);
                    list.add(checkSheetDimension);
                }
            }

            sheet.setDimensionList(list);

        }else {
            sheet.setDimensionList(list);
        }
        //响应一个创建好的本地 word 文档地址
        String file = checkSheetExportService.exportEvaluateReport(sheet);
        String fileName = developDetails.getChildrenName()+ DateUtil.convertStr(new Date());

        FileOutputStream fileOutputStream = null;
        String uploadedResult ="";
        try {
            File outputFile = new File(file);
            String uploadPath = "teach/file/children_export_excel/" + DateTime.now().toString("yyyy-MM") + "/" + fileName + ".doc";
            String relativePath = ossProcessService.aliyunOssUpload(uploadPath, outputFile);
            uploadedResult = IMG_SERVICE_PREFIX + relativePath;
            outputFile.deleteOnExit();
            outputFile.delete();
            fileOutputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return StatusResponse.success(uploadedResult);
    }
}
